var express = require('express');
var router = express.Router();

/* GET home page. */
router.all('/test', function (req, res) {
    console.log('====test====');
    res.end('test ok');
});
router.get('/', function (req, res) {
    console.log('=====');
    //get url,交由合适的function处理
    var method = req.method;
    console.log('method=' + method);
    //var path = req.router.path;

    if (method == "GET") {
        var query = req.query;
        console.log('query=' + query);
    } else if ("POST" == method) {

    }
    res.render('index', { title: 'Express' });
});
router.all('/helloworld', function (req, res) {
    //get url,交由合适的function处理
    var method = req.method;
    console.log('method=' + method);
    //var path = req.router.path;

    if (method == "GET") {
        var query = req.query;
        console.log('query=' + query);
    } else if ("POST" == method) {

    }
    res.render('helloworld', { title: 'hello world' });
});

/* GET Userlist page. */
router.get('/userlist', function (req, res) {
    var db = req.db;
    var collection = db.get('usercollection');
    collection.find({}, {}, function (e, docs) {
        res.render('userlist', {
            "userlist": docs
        });
    });
});

/* GET New User page. */
router.get('/newuser', function (req, res) {
    res.render('newuser', { title: 'Add New User' });
});
/* POST to Add User Service */
router.post('/adduser', function (req, res) {

    // Set our internal DB variable
    var db = req.db;

    // Get our form values. These rely on the "name" attributes
    var userName = req.body.username;
    var userEmail = req.body.useremail;
    console.log('adduser: name=' + userName + ",email=" + userEmail);

    // Set our collection
    var collection = db.get('usercollection');

    // Submit to the DB
    collection.insert({
        "username": userName,
        "email": userEmail
    }, function (err, doc) {
        if (err) {
            // If it failed, return error
            res.send("There was a problem adding the information to the database.");
        }
        else {
            // If it worked, set the header so the address bar doesn't still say /adduser
            res.location("userlist");
            // And forward to success page
            res.redirect("userlist");
        }
    });
});
module.exports = router;
